package com.prj.ufdm.demo.tutorial.socket;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Random;

public class TestSocketClient {

	private static String HOST="127.0.0.1";
	private static int PORT=9999;
	
	public static void main(String[] args) throws Exception {
		
		Socket socket = null;
		String sendMessage = "hello"+new Random().nextInt(100);
		try {
			socket = new Socket(HOST, PORT);
			
			OutputStream outputStream = socket.getOutputStream();
			InputStream inputStream = socket.getInputStream();
			
			outputStream.write(sendMessage.getBytes());
			System.out.println("发送请求(" + HOST + ":"+ PORT +"):" + sendMessage);
			
			String receiveMessage = new String(readStream(inputStream),"UTF-8");
			System.out.println("接收结果：" + receiveMessage);
			
			outputStream.close();
			inputStream.close();
		}
		catch(Exception er) {
			er.printStackTrace();
		}
		finally {
			if(socket!=null) {
				socket.close();
			}
		}
	}
	
	
	public static byte[] readStream(InputStream inStream) throws Exception {
		int count = 0;
		while (count == 0) {
			count = inStream.available();
		}
		byte[] b = new byte[count];
		inStream.read(b);
		return b;
	}

}
